import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo, logout } from '@/api/login'
import Profile from '@/assets/images/profile.jpg'

const useUserStore = defineStore('user', () => {
  const name = ref('')
  const avatar = ref('')
  const token = ref(getToken())
  const userInfo = ref({})
  const roles = ref([])
  const permissions = ref([])

  const Login = (data) => {
    const username = data.username.trim()
    const password = data.password.trim()
    const code = data.code
    const uuid = data.uuid
    return new Promise((resolve, reject) => {
      login(username, password, code, uuid)
        .then((res) => {
          setToken(res.token)
          token.value = res.token
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  const GetInfo = () => {
    return getInfo().then((res) => {
      const data = res.user
      avatar.value = data.avatar ? import.meta.env.VITE_APP_BASE_API + data.avatar : Profile

      if (data.roles && data.roles.length > 0) {
        // 验证返回的roles是否是一个非空数组
        roles.value = data.roles
        permissions.value = data.permissions
      } else {
        roles.value = ['ROLE_DEFAULT']
      }
      name.value = data.username
      return data
    })
  }

  const LogOut = () => {
    return logout().then(() => {
      token.value = ''
      roles.value = []
      permissions.value = []
      removeToken()
      return Promise.resolve()
    })
  }

  return {
    name,
    avatar,
    userInfo,
    token,
    roles,
    permissions,
    Login,
    GetInfo,
    LogOut
  }
})

export default useUserStore
